package cn.hwadee.muying.commons.utils.beetl;

import cn.hwadee.muying.commons.utils.spring.SpringContextHolder;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.ext.spring.BeetlGroupUtilConfiguration;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Set;

/**
 * @描述:
 * @作者: Pengo.Wen
 * @日期: 2017-09-16 21:39
 * @版本: v1.0
 */
public class ExportService {

    /**
     *
     * @Title: createDoc
     * @Description: 创建doc
     * @param @param tlPath 模板路径
     * @param @param paramMap 参数
     * @param @param Path  文件保存路径
     * @return void
     * @throws
     */
    public static void createDoc(String tlPath, Map<String, Object> paramMap, String path) {
        PrintWriter pw = null;
        try {
            GroupTemplate groupTemplate = ((BeetlGroupUtilConfiguration) SpringContextHolder.getApplicationContext().getBean("xmlbeetlConfig")).getGroupTemplate();

            Template template = groupTemplate.getTemplate(tlPath);

            //添加数据到上下文中
            Set<String> keys = paramMap.keySet();
            for (String key : keys) {
                template.binding(key, paramMap.get(key));
            }

            File file = new File(path);

            // 创建目录
            File dir = file.getParentFile();
            if (!dir.exists()) {
                dir.mkdirs();
            }

            pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));
            template.renderTo(pw);//template.renderTo(os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(pw != null ){
                pw.close();
            }
        }
    }

}
